

export enum MsgType
{
    GameLoading="GameLoading",
    GameLoadOver="GameLoadOver",
    GameStart="GameStart",
}

class MsgFunction
{
    FucId:string="";
    CallFuc:Function=null;
}


export default class MsgDispatcher 
{

   private static m_registeredMsgs: { [key: string]:Array<MsgFunction>; } ={};

   public static Register( msgName:string,fucId:any,onMsgReceived:Function):void
   {
       
        if(this.m_registeredMsgs[msgName]==null)
        {
            this.m_registeredMsgs[msgName]=[];
        }
        if (this.m_registeredMsgs[msgName]) 
        {
            for (let index = 0; index < this.m_registeredMsgs[msgName].length; index++) {
                const element = this.m_registeredMsgs[msgName][index];
                if (element.FucId==fucId&&onMsgReceived.name==element.CallFuc.name) 
                {
                    console.warn("该方法已存在！！！无需重复注册 "+element.FucId+" "+element.CallFuc.name);
                    return;
                }
            }   
        }
        let callback=new MsgFunction();
        callback.FucId=fucId;
        callback.CallFuc=onMsgReceived;
        this.m_registeredMsgs[msgName].push(callback);
   }


   public static  UnRegisterAll( msgName:string)
   {  
       if(this.m_registeredMsgs[msgName]!=null)
       {
           delete this.m_registeredMsgs[msgName];      
       }
   }


   public static  UnRegister(msgName:string,fucId, onMsgReceived:Function)
   {
       let functionArray=this.m_registeredMsgs[msgName];
       let fucIndex=-1;
        if(functionArray!=null)
        {
           for (let index = 0; index < functionArray.length; index++) {
               const element = functionArray[index];
               if (element.CallFuc.name==onMsgReceived.name&&element.FucId==fucId ) 
               {
                    fucIndex=index;
                 //  console.log("UnRegister "+onMsgReceived.name);
                   break;
               }
           }
            if( fucIndex>-1)
            {
                this.m_registeredMsgs[msgName].splice(fucIndex);
            }
            if(functionArray.length<1){
                delete this.m_registeredMsgs[msgName];
            }
        }
   }


   public static  Send(msgName:string,data:any=null)
   {
       if (this.m_registeredMsgs[msgName]!=null)
       {
            this.m_registeredMsgs[msgName].forEach(func => {
            func.CallFuc(data);
            });
       }
       else
       {
           console.log("error:"+msgName+" 不存在当前数组中");
       }
   }
}